<template>
  <a-select
    multiple
    :placeholder="selectPlaceholder"
    :max-tag-count="maxTagCount"
    v-model="selectId"
    :show-header-on-empty="true"
    @change="handelChange as any"
  >
    <template #header>
      <div class="search-select-container">
        <a-input v-autoFocus style="border: 0" :placeholder="placeholder" v-model="keyword" @press-enter="handleSearchSelect" />
        <GiSvgIcon name="searchBox-icon" size="24" style="margin-right: 18px; cursor: pointer" @click="handleSearchSelect" />
      </div>
    </template>
    <a-option v-for="optItem in selectList" :value="optItem[config.value]" :key="optItem[config.value]">
      {{ optItem[config.label] }}
    </a-option>
  </a-select>
</template>

<script setup lang="ts">
import { debounce } from "lodash";
const props = defineProps({
  selectPlaceholder: {
    type: String,
    default: "请选择"
  },
  /**
   * 输入框占位
   */
  placeholder: {
    type: String,
    default: "请输入关键词"
  },
  /**
   * 默认选中值
   */
  defaultSelectId: {
    type: Array,
    default: () => []
  },
  /**
   * 默认选中列表
   */
  defaultSelectList: {
    type: Array,
    default: () => []
  },
  /**
   * 请求接口
   */
  requestApi: {
    type: Function,
    required: true
  },
  /**
   * 请求参数
   */
  params: {
    type: Object,
    default: () => ({})
  },
  /**
   * 配置项
   */
  config: {
    type: Object,
    default: () => ({})
  },
  maxTagCount: {
    type: Number,
    default: 2
  }
});
const emit = defineEmits(["changeSelect"]);

const config = ref({
  label: "label",
  value: "value",
  keyword: "keyword",
  debounceTime: 500,
  ...props.config
});
const keyword = ref("");
const selectId = ref(props.defaultSelectId);
const selectList = ref(props.defaultSelectList) as any;

/**
 * 搜索
 */
const cloneSelectList = ref([]) as any;
const getSelectList = async (type: any) => {
  const { data } = await props.requestApi({
    [config.value.keyword]: type == "search" ? keyword.value : "",
    ...props.params
  });
  const list = Array.isArray(data) ? data : [];

  const filterSeletedList = cloneSelectList.value.filter((item: any) => selectId.value.includes(item[props.config.value]));
  selectList.value = [...list, ...filterSeletedList];
  if (type == "all") {
    cloneSelectList.value = list;
  }
};
const handleSearchSelect = debounce((type: any) => getSelectList("search"), config.value.debounceTime);
/**
 * 选择
 */
const handelChange = (e: any) => {
  const selectArr = cloneSelectList.value.filter((item: any) => e.includes(item[props.config.value]));
  emit("changeSelect", selectArr);
};

getSelectList("search");
getSelectList("all");
</script>

<style scoped lang="scss">
@import "selectSearch";
</style>
